package com.yun.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.yun.reggie.common.BaseContext;
import com.yun.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpRequest;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 检查用户是否完成登录，过滤所有请求
 * @WebFilter 将类声明为过滤器
 * @author 肖宇航
 */
@Slf4j
@WebFilter(filterName = "LoginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    //路径匹配器，支持匹配通配符
    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //向下转型
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        String requestURI = request.getRequestURI();

        //拦截到请求：/backend/page/login/login.html

        /**
         * 定义一些请求路径，用于用户访问，直接放行
         * 至于静态资源中的前端页面，只要不访问数据，就让他访问
         * 也就是只拦截Controller中的请求，对于页面请求不拦截
         */
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/login",
                "/user/sendMsg",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };

        //如果请求路径不需要处理，直接放行 || 判断登录状态,已登录--放行
        if (check(urls,requestURI) || request.getSession().getAttribute("employee") != null){
            log.info("本次请求：{}不需要处理",requestURI);
            BaseContext.setCurrentId((Long) request.getSession().getAttribute("employee"));
            filterChain.doFilter(request,response);
            return;
        }else if (check(urls,requestURI) || request.getSession().getAttribute("user") != null){
            //上面是判断后台系统中用户是否登录，下面是判断移动端用户是否登录.对于设置的放行资源都执行放行
            log.info("本次请求：{}不需要处理",requestURI);
            BaseContext.setCurrentId((Long) request.getSession().getAttribute("user"));
            filterChain.doFilter(request,response);
            return;
        }

        //如果未登录，通过输出流方式向页面返回数据
        log.info("拦截到请求{}，用户未登录！",requestURI);
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
        //log.info("拦截到请求：{}",requestURI);
    }


    public boolean check(String[] urls,String requestURI){
        for (String url:urls) {
            boolean res = PATH_MATCHER.match(url, requestURI);
            if (res == true){
                //匹配成功
                return true;
            }
        }
        return false;
    }
}
